package cn.zb.utils;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by liuyang on 15/3/23.
 */
public class StringUtil {

    private static final String REG_EMAIL = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";

    public static boolean isEmail(String string) {
        Pattern regex = Pattern.compile(REG_EMAIL);
        Matcher matcher = regex.matcher(string);
        boolean isMatched = matcher.matches();
        return isMatched;
    }

    public static String getValue(String str) {
        if (null == str) {
            return "";
        }
        if ("".equals(str) || "null".equals(str) || "NULL".equals(str)) {
            return "";
        }
        return str.trim();
    }

    public static boolean isEmpty(String str) {
        return "".equals(getValue(str));
    }

    static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    static final char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    static final Random rand = new Random();

    /**
     * 产生随机字符串
     *
     * @param length
     * @return
     */
    public static String randomString(int length) {
        StringBuffer sb = new StringBuffer();
        for (int loop = 0; loop < length; loop++)
            sb.append(hexDigits[rand.nextInt(hexDigits.length)]);
        return sb.toString();
    }

    /**
     * 产生随机字符串
     *
     * @param length
     * @return
     */
    public static String randomNumber(int length) {
        StringBuffer sb = new StringBuffer();
        for (int loop = 0; loop < length; loop++)
            sb.append(digits[rand.nextInt(digits.length)]);
        return sb.toString();
    }
}
